<template>
  <c-form
    ref="formRef"
    label-width="100px"
    isDialog
    :model="formData"
    :rows="formRows"
    @submit="onSubmit"
  ></c-form>
</template>

<script setup name="group-create" lang="jsx">
import { ref, computed } from 'vue';

// components
import { ElMessage } from 'element-plus';

// modal,pinia
import { useModalStore } from '@/pinia/modules/modal';
const modalStore = useModalStore();

import { useFetch } from '@/hooks/useFetch/index.js';

// api
import { createTextGroup, editeTextGroup } from '@/apis/text';

const emit = defineEmits(['refresh']);

const props = defineProps({
  // 0 普通用户 1 admin
  userType: {
    type: [String, Number],
    default: 0,
  },
});

const formData = ref({
  _id: '',
  name: '',
  group_sort: 0,
});

const formRows = ref([
  { formType: 'input', prop: 'name', label: '分组名称:' },
  { formType: 'input-number', prop: 'group_sort', label: '分组权重:' },
]);

// 获取传递弹窗的数据
const modalData = modalStore.getModal();
if (modalData._id) {
  console.log(modalData, 'modalData');
  formData.value._id = modalData._id;
  formData.value.name = modalData.name;
  formData.value.group_sort = modalData.group_sort;
}

const formRef = ref(null);
const onSubmit = async (values, instance, done) => {
  instance.loading = true;
  console.log(formData.value, 'formData');

  if (formData.value._id) {
    const groupRes = await editeTextGroup({
      ...formData.value,
    });

    if (groupRes.code == 0) {
      ElMessage.success('添加成功');
      modalStore.closeModal('text-group-create');
    }
  } else {
    let obj = { ...formData.value };

    if (props.userType) {
      obj['userid'] = -1;
    }

    const groupRes = await createTextGroup(obj);

    if (groupRes.code == 0) {
      ElMessage.success('添加成功');
      modalStore.closeModal('text-group-create');
    }
  }

  emit('refresh');

  done();
  instance.loading = false;
};
</script>

<style lang="scss" scoped></style>
